<template>
  <div class="sideTree">
    <div class="treeHeader" v-if="useButton">
      <el-button type="primary" @click="onAddClick">新增</el-button>
      <el-button type="danger" @click="onDelClick">删除</el-button>
    </div>
    <div class="treeHeader" v-if="title" :style="{ backgroundColor: theme }">
      {{ title }}
    </div>
    <div class="head-container">
      <el-input
        v-model="filterVal"
        clearable
        prefix-icon="Search"
        style="margin-bottom: 20px"
      />
    </div>
    <div class="head-container" :style="{ height, overflow: 'auto' }">
      <el-tree
        :data="treeData"
        :props="propsOptions"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        ref="deptTreeRef"
        :node-key="nodeKey"
        highlight-current
        default-expand-all
        @node-click="handleNodeClick"
      />
    </div>
  </div>
</template>

<script setup>
import useSettingsStore from "@/store/modules/settings";
const theme = computed(() => useSettingsStore().theme);
const props = defineProps({
  treeData: {
    type: Array,
    default: () => [],
  },
  propsOptions: {
    type: Object,
    default: () => ({
      label: "label",
      children: "children",
    }),
  },
  nodeKey: {
    type: [String, Number],
    default: "id",
  },
  title: {
    type: String,
    default: "",
  },
  useButton: {
    type: Boolean,
    default: false,
  },
  height: {
    type: [String, Number],
    default: "100%",
  },
});

const emit = defineEmits(["nodeClick", "onAddClick", "onDelClick"]);
const deptTreeRef = ref();
const filterVal = ref("");
const selectNode = ref({});
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
const onAddClick = () => {
  emit("onAddClick");
};
const onDelClick = () => {
  emit("onDelClick", selectNode.value);
};
function handleNodeClick(data) {
  selectNode.value = data;
  emit("nodeClick", { key: data[props.nodeKey], node: data });
}
watch(filterVal, (val) => {
  deptTreeRef.value.filter(val);
});
</script>

<style lang="scss" scoped>
.treeHeader {
  height: 35px;
  line-height: 35px;
  color: #fff;
  font-weight: 650;
  padding-left: 15px;
  margin-bottom: 10px;
}

.sideTree {
  padding-right: 5px;
  border-right: 2px solid #eee;
  border-bottom: 2px solid #eee;
  overflow: auto;
}
</style>
